﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NHibernate.Transform;
using NHibernate.Properties;
using System.Collections;
using NHibernate;

namespace BullTasDesaDal.Service
{
    class AliasToBeanResultTransformerWithFactoryMethod<T> : IResultTransformer
    {
        private Func<T> _factory;
        private readonly IPropertyAccessor _propertyAccessor;
        private ISetter[] _setters;

        public AliasToBeanResultTransformerWithFactoryMethod(Func<T> factory)
        {
            _factory = factory;
            this._propertyAccessor = new ChainedPropertyAccessor(
                new IPropertyAccessor[]
            {
                PropertyAccessorFactory.GetPropertyAccessor(null), 
                PropertyAccessorFactory.GetPropertyAccessor("field")
            });
        }

        public IList TransformList(IList collection)
        {
            return collection;
        }

        public object TransformTuple(object[] tuple, string[] aliases)
        {
            object obj2;
            try
            {
                if (this._setters == null)
                {
                    this._setters = new ISetter[aliases.Length];
                    for (int j = 0; j < aliases.Length; j++)
                    {
                        string propertyName = aliases[j];
                        if (propertyName != null)
                        {
                            this._setters[j] = this._propertyAccessor.GetSetter(typeof(T), propertyName);
                        }
                    }
                }
                obj2 = _factory();
                for (int i = 0; i < aliases.Length; i++)
                {
                    if (this._setters[i] != null)
                    {
                        this._setters[i].Set(obj2, tuple[i]);
                    }
                }
            }
            catch (InstantiationException exception)
            {
                throw new HibernateException("Could not instantiate result class: " + typeof(T).FullName, exception);
            }
            catch (MethodAccessException exception2)
            {
                throw new HibernateException("Could not instantiate result class: " + typeof(T).FullName, exception2);
            }
            return obj2;
        }

    }
}
